package com.qf.demo;

import java.sql.*;

/**
 * @Description: 公用常量
 * @Data: 2022/8/26 10:44
 * @Pacakge: com.qf.demo
 * @ClassName: Demo
 * @Author: fan
 *传统jdbc
 */
public class Demo {
    public static void main(String[] args) {
        Connection connection = null;//数据库连接对象
        PreparedStatement preparedStatement = null;//执行预编译对象
        ResultSet resultSet =null;//结果集对象

        try {
            //1>导包
            //2>注册驱动
            Class.forName("com.mysql.jdbc.Driver");//编译期不会报错,运行时报错
            //解耦:在实际开发中,我们应该做到的是编译期不依赖,运行期依赖
            //通过反射避免使用new关键字
            //通过读取配置文件的方式,获取全路径类名
            //工厂解耦:反射+XML解析
           //DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //如果将包删除,则编译期就会出现错误
            //3>获取数据库连接对象
            connection = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/racemall",
                    "root",
                    "f971014");
            //4>准备sql语句
            String sql = "select * from admin where id = ?";//占位符?,防止sql注入攻击
            //5>获取执行对象并执行sql语句
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1,2);
            //6>执行sql语句
            resultSet = preparedStatement.executeQuery();
            //遍历结果集
            while(resultSet.next()){
                int id = resultSet.getInt("id");
                String username = resultSet.getString("username");
                String password = resultSet.getString("password");
                System.out.println("id:"+id+"username:"+username+"password:" + password);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                if (resultSet != null){
                    resultSet.close();
                }
                if (preparedStatement != null){
                    preparedStatement.close();
                }
                if (connection != null){
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
